#!/sbin/sh
# arg 1 is recovery api version, generally 3.
# arg 2 is the pipe fd, to the recovery binary.
# communicate with it using the recovery api.
# arg 3 is the zip file

mount /system
mount /data
DIR="$PWD"

echo -n -e 'ui_print Deleting old files...\n' > /proc/self/fd/$2
echo -n -e "ui_print\n" > /proc/self/fd/$2
cleanup () {
    cd "$1"
    for i in ./*; do
        if [ -L "$i" ] && ([ "`./busybox ls -l \"$i\"|./busybox grep busybox`" ] || [ ! -e "$i" ]); then
            rm "$i"
        fi
    done
    rm busybox 2> /dev/null
    rm /data/local/busybox 2> /dev/null
    cd "$DIR"
}
cleanup /system/bin
cleanup /system/xbin

echo -n -e 'ui_print Extracting busybox...\n' > /proc/self/fd/$2
echo -n -e "ui_print\n" > /proc/self/fd/$2
cp /cache/busybox /system/xbin/busybox
if [ $? -eq 0 ]; then
    echo -n -e 'ui_print Setting permissions...\n' > /proc/self/fd/$2
    echo -n -e "ui_print\n" > /proc/self/fd/$2
    chown 0:2000 /system/xbin/busybox
    chmod 755 /system/xbin/busybox
else
    rm /system/xbin/busybox 2> /dev/null
    cp /cache/busybox /data/local/busybox
    echo -n -e 'ui_print Setting permissions...\n' > /proc/self/fd/$2
    echo -n -e "ui_print\n" > /proc/self/fd/$2
    chmod 755 /data/local/busybox
    ln -s /data/local/busybox /system/xbin/busybox
fi

echo -n -e 'ui_print Installing busybox applets...\n' > /proc/self/fd/$2
echo -n -e "ui_print\n" > /proc/self/fd/$2
cd /system/xbin
./busybox --install -s .
cd $DIR

rm /cache/busybox.zip
rm /cache/busybox
rm /cache/recovery/command &> /dev/null
rm /cache/recovery/openrecoveryscript &> /dev/null

umount /system
umount /data
